var SceneLayer = function(options) {
	this.ctx=options.ctx;
	this.editor=options.editor;
	this.globe = options.editor.globe;
	this.sceneId=options.sceneId;
	this.treeId=null;
	this.roamObj=null;
	this.dIndex;
	this.isOpen=false;
	return this;
}

SceneLayer.prototype.init = function() {
	var _this = this;
}

SceneLayer.prototype.open = function() {
	var _this = this;
	if (_this.isOpen) {
		return;
	}
	layer.load(2);
	var res = common_ajax.ajaxFunc('get', _this.ctx + "/scene/layer/tree", {
		
	}, "html", null);
	layer.closeAll();
	if (!res) {
		layer.alert('系统异常！');
		return;
	}
	
	layer.open({
		id: 'sceneLayer',
		title: '场景树',
		type: 1,
		area: '230px',
		content: res,
		shade: 0,
		offset: 'l',
		fixed: true,
		move: true,
		skin: 'layui-layer layui-layer-adminRight layui-layer-city',
		success: function(layero, dIndex) {
			_this.isOpen = true;
			_this.dIndex=dIndex;
			$(layero).children('.layui-layer-content').css('overflow', 'hidden');
			$(layero).children('.layui-layer-content').css('height', 'calc(100% - 40px)');
			form.render();
			_this.renderTool();
			_this.initTree();
		},
		end: function() {
			_this.isOpen = false;
		}
	});
}
SceneLayer.prototype.close = function() {
	var _this = this;
	if(this.dIndex){
		layer.close(this.dIndex) 
	}
	_this.treeId=null;
}

SceneLayer.prototype.initTree = function() {
	var _this = this;
	_this.treeId='sceneLayerTree';
	let rMenu = $("#rMenu");
	var setting = {
		async: {
			enable: true,
			url: _this.ctx + "/scene/layer/getTree?sceneId="+_this.sceneId,
			autoParam: ["id", "name=n", "level=lv", "type=type"],
			dataFilter: filter,
		},
		view: {
			dblClickExpand: false
		},
		check: {
			enable: true,
			chkboxType :{  "Y" : "s", "N" : "s" } //Y:勾选（参数：p:影响父节点），N：不勾（参数s：影响子节点）[p 和 s 为参数]
		},
		edit: {
			enable: true,
			showRemoveBtn: false,
			showRenameBtn: false,
		},
		callback: {
			onClick: onClick,
			onCheck: onCheck,
			beforeDrag: beforeDrag,
			beforeDrop: beforeDrop,
			onDrop: onDrop,
			onRightClick: OnRightClick
		}
	};

	function filter(treeId, parentNode, childNodes) {
		if (!childNodes)
			return null;
		for (var i = 0, l = childNodes.length; i < l; i++) {
			childNodes[i].name = childNodes[i].name?childNodes[i].name.replace(/\.n/g, '.'):'未命名';
		}
		return childNodes;
	}

	function onCheck(e, treeId, treeNode) {
		if(treeNode.isParent){
			getAllChildrenNodes(treeNode);
		}else{
			showOrHide(treeNode)
		}
	}
	
	function onClick(e, treeId, treeNode) {
		if('-1'===treeNode.type || '-2'===treeNode.type){
			_this.flyToLayer(treeNode);
			return;
		}
		let obj=_this.globe.getById(treeNode.id);
		if(obj){
			_this.globe.flyToThing(obj);
		}else{
			layer.msg('对象不存在场景中，请确认是否渲染！');
		}
	}
	
	function onDrop(e,treeId, treeNode,targetNode){
		if(treeNode && targetNode){
			var formData={};
			formData['sceneLayer.id']=treeNode[0].id;
			formData['sceneLayer.parentId']=targetNode.id;
			layer.load(2);
			var res = common_ajax.ajaxFunc('post', _this.ctx + "/scene/layer/save",formData, "json", null);
	        layer.closeAll('loading');
	        if (res.code == 200) {
	            _this.refreshNode(res.data.id)
	        } else {
	            layer.msg(res.message, {icon: 2});
	        }
		}
	}
	
	function beforeDrag(treeId, treeNode){
		/*if(treeNode &&'-1'===treeNode[0].type){
			return false;
		}*/
	}
	
	function beforeDrop(treeId, treeNode,targetNode){
		if(targetNode && '-1'!=targetNode.type && '-2'!=targetNode.type && 'plan'!=targetNode.type){
			return false;
		}
	}
	
	function OnRightClick(event, treeId, treeNode) {
		$.fn.zTree.getZTreeObj(_this.treeId).selectNode(treeNode);
		showRMenu(treeNode.type, event.clientX, event.clientY);
	}

	function showRMenu(type, x, y) {
		$("#rMenu ul").show();
		if (type=="-1" || type=="-2") {
			$("#m_del").hide();
			$("#m_edit").hide();
			$("#t_group").hide();
			$("#f_edit").show();
			$("#f_view").show();
			$("#f_del").show();
			$("#p_edit").hide();
			$("#p_del").hide();
			$("#p_view").hide();
			$("#p_pend").hide();
			$("#p_stop").hide();
			$("#p_config").hide();
		} else if(type=="1"){
			$("#m_edit").show();
			$("#m_del").show();
			$("#t_group").show();
			$("#f_edit").hide();
			$("#f_view").hide();
			$("#f_del").hide();
			$("#p_edit").hide();
			$("#p_del").hide();
			$("#p_view").hide();
			$("#p_pend").hide();
			$("#p_stop").hide();
			$("#p_config").hide();
		}else if(type=="plan"){
			$("#m_del").hide();
			$("#m_edit").hide();
			$("#t_group").hide();
			$("#f_edit").hide();
			$("#f_view").hide();
			$("#f_del").hide();
			$("#p_del").show();
			$("#p_edit").show();
			$("#p_view").show();
			$("#p_pend").show();
			$("#p_stop").show();
			$("#p_config").show();
		}else {
			$("#m_edit").show();
			$("#m_del").show();
			$("#t_group").hide();
			$("#f_edit").hide();
			$("#f_view").hide();
			$("#f_del").hide();
			$("#p_edit").hide();
			$("#p_del").hide();
			$("#p_view").hide();
			$("#p_pend").hide();
			$("#p_stop").hide();
			$("#p_config").hide();
		}
        y += document.body.scrollTop;
        x += document.body.scrollLeft;
        rMenu.css({"top":y+"px", "left":x+"px", "visibility":"visible"});
		$("body").bind("mousedown", onBodyMouseDown);
	}
	
	function onBodyMouseDown(event){
		if (!(event.target.id == "rMenu" || $(event.target).parents("#rMenu").length>0)) {
			rMenu.css({"visibility" : "hidden"});
		}
	}
	
	$('#f_edit').click(function() {
		var nodes = $.fn.zTree.getZTreeObj(_this.treeId).getSelectedNodes();
		if(nodes && nodes.length>0){
			_this.showEditFolder(nodes[0]);
		}
	});
	
	$('#p_edit').click(function() {
		var nodes = $.fn.zTree.getZTreeObj(_this.treeId).getSelectedNodes();
		if(nodes && nodes.length>0){
			_this.showEditPlan(nodes[0]);
		}
	});
	
	$('#p_del').click(function() {
		var nodes = $.fn.zTree.getZTreeObj(_this.treeId).getSelectedNodes();
		if(nodes && nodes.length>0){
			deleteLayer(nodes[0]);
		}
	});
	
	$('#f_view').click(function() {
		var nodes = $.fn.zTree.getZTreeObj(_this.treeId).getSelectedNodes();
		if(nodes && nodes.length>0){
			settingView(nodes[0]);
		}
	});
	
	$('#f_del').click(function() {
		var nodes = $.fn.zTree.getZTreeObj(_this.treeId).getSelectedNodes();
		if(nodes && nodes.length>0){
			deleteLayer(nodes[0]);
		}
	});
	
	$('#m_del').click(function() {
		var nodes = $.fn.zTree.getZTreeObj(_this.treeId).getSelectedNodes();
		if(nodes && nodes.length>0){
			deleteLayer(nodes[0]);
		}
	});
	
	$('#m_edit').click(function() {
		var nodes = $.fn.zTree.getZTreeObj(_this.treeId).getSelectedNodes();
		if(nodes && nodes.length>0){
			_this.showEditModel(nodes[0]);
		}
	});
	
	$('#t_group').click(function() {
		var nodes = $.fn.zTree.getZTreeObj(_this.treeId).getSelectedNodes();
		if(nodes && nodes.length>0){
			_this.showEditFolder(nodes[0],nodes[0].id);
		}
	});
	
	/**预览**/
	$('#p_view').click(function() {
		planRoam();
	});
	
	/**暂停**/
	$('#p_pend').click(function() {
		var nodes = $.fn.zTree.getZTreeObj(_this.treeId).getSelectedNodes();
		if(nodes && nodes.length>0){
			_this.showEditFolder(nodes[0],nodes[0].id);
		}
	});
	
	/**停止**/
	$('#p_stop').click(function() {
		var nodes = $.fn.zTree.getZTreeObj(_this.treeId).getSelectedNodes();
		if(nodes && nodes.length>0){
			_this.showEditFolder(nodes[0],nodes[0].id);
		}
	});
	
	$('#p_config').click(function() {
		var nodes = $.fn.zTree.getZTreeObj(_this.treeId).getSelectedNodes();
		if(nodes && nodes.length>0){
			_this.showPlanEdit(nodes[0],nodes[0].id);
		}
	});
	
	
	
	function getAllChildrenNodes(treeNode){
		if(treeNode.isParent){
			var childrenNodes = treeNode.children;
			if (childrenNodes){
				for (var i = 0; i < childrenNodes.length; i++) {
					if(childrenNodes[i].isParent){
						getAllChildrenNodes(childrenNodes[i]);
					}else{
						showOrHide(childrenNodes[i])
					}
				}
			}
			showOrHide(treeNode)
		}
	}
	
	function settingView(treeNode){
		var v = _this.editor.VFG.Util.getVisualAngle(_this.editor.globe.viewer);
		if (v) {
			layer.load(2);
			var res = common_ajax.ajaxFunc('post', _this.ctx + "/scene/layer/save",{
				'sceneLayer.id':treeNode.id,
				'sceneLayer.heading':v.heading,
				'sceneLayer.pitch':v.pitch,
				'sceneLayer.roll':v.roll,
				'sceneLayer.x':v.position.x,
				'sceneLayer.y':v.position.y,
				'sceneLayer.z':v.position.z,
			}, "json", null);
			if (200 == res.code) {
				layer.closeAll('loading');
				layer.msg(res.message, { icon: 1 });
				return true;
			} else {
				layer.msg("设置失败，请刷新重试！", { icon: 2 });
				return false;
			}
		}
	}
	
	function deleteLayer (treeNode) {
		layer.confirm('确定要删除“【<span style="color:red;">' + treeNode.name.replace(/\(.*?\)/g,'') + '</span>】”吗？', {
			shade: .1
		}, function(index) {
			layer.close(index);
			layer.load(2);
			var res = common_ajax.ajaxFunc('get', _this.ctx + "/scene/layer/delete", { layerId: treeNode.id }, "json", null);
			layer.closeAll('loading');
			if (200 == res.code) {
				layer.msg(res.message, { icon: 1 });
				var zTree = $.fn.zTree.getZTreeObj(_this.treeId);
				zTree.reAsyncChildNodes(null, "refresh");
				_this.globe.remove(treeNode.id);
				var children = treeNode.children;
				if(children && children.length>0){
					children.forEach(function (value){
						_this.globe.remove(value.id);
					});
				}
				return true;
			} else {
				layer.msg(res.message, { icon: 2 });
				return false;
			}
		}, function(index) {
			layer.close(index);
			return false;
		});
	}
	
	function showOrHide(treeNode){
		if(treeNode.type=='-2'){
			let tobj=_this.globe.getById(treeNode.parentId);
			if(tobj){
				if(treeNode.checked){
					tobj.showFeatureGroup(treeNode.code);
				}else{
					tobj.hideFeatureGroup(treeNode.code);
				}
			}
		}else {
			common_ajax.ajaxAsyncFunc('post', _this.ctx + "/scene/layer/save",{
				'sceneLayer.id':treeNode.id,
				'sceneLayer.show':treeNode.checked?'1':'0',
			}, "json", function(res){
				if (200 == res.code) {
					if(treeNode.checked){
						_this.globe.render(res.data,_this.ctx);
					}else{
						_this.globe.remove(treeNode.id);
					}
				}
			});
		}
	}
	
	function planRoam(){
		let nodes = $.fn.zTree.getZTreeObj(_this.treeId).getSelectedNodes();
		if(nodes && nodes.length>0){
			let res = common_ajax.ajaxFunc('post', _this.ctx + "/scene/plan/getSubLine",{id:nodes[0].id}, "json", null);
	        layer.closeAll('loading');
	        if (res.code == 200) {
	            _this.roamObj = _this.globe.planRoam({
	            	lines:JSON.parse(res.data.positions),
	            	duration:3600,
	            	isPathShow:true
	            });
	           setTimeout(function() {
			        if(_this.roamObj){
		            	_this.roamObj.StartRoaming();
		            }
			    }, 6000);
	        } else {
	            layer.msg(res.message, {icon: 2});
	        }
		}
	}
	_this.zTree=$.fn.zTree.init($('#'+_this.treeId), setting);
}

SceneLayer.prototype.showEditModel=function(nData){
	let _this=this;
	$("#rMenu").css({"visibility" : "hidden"});
	let obj=_this.globe.getById(nData.id);
	if(!obj){
		layer.msg('对象不存在场景中，请确认是否渲染！');
		return;
	}
	if('1'==nData.type) {
		_this.editor.scene3dtitle.editTModel(obj);
	}
	else if('2'==nData.type){
		_this.editor.sceneModelLibrary.editPModel(obj);
	}
	else if('3'==nData.type) {
		_this.editor.sceneVideoFusion.editVModel(obj);
	}else {
		
	}
}

SceneLayer.prototype.showEditFolder=function(nData,parentId){
	let _this=this;
	_this.hideRMenu();
    layer.open({
        type: 1,
        title: (nData ? '修改' : '新增') + '分组',
        content: $('#sceneLayerEditScript').html(),
		offset: '40px',
		area: '280px',
        skin: 'layui-layer layui-layer-city',
        success: function (layero, dIndex) {
			if(nData)
				nData.name = nData.name.replace(/\(.*?\)/g,'');
			if(!parentId){
				form.val('sceneLayerForm', nData);
			}
            form.on('submit(submitSceneLayerForm)', function (data) {
                layer.load(2);
                var formData={}; 
                for(var key in data.field){
                	formData['sceneLayer.'+key]=data.field[key];
                }
                if(!data.field['parentId']){
                	formData['sceneLayer.parentId']=parentId||_this.sceneId;
                }
				if(parentId){
					formData['sceneLayer.type']='-2';
				}
                formData['sceneLayer.sceneId']=_this.sceneId;
    			var res = common_ajax.ajaxFunc('post', _this.ctx + "/scene/layer/save",formData, "json", null);
                layer.closeAll('loading');
                if (res.code == 200) {
                    layer.close(dIndex);
                    layer.msg(res.message, {icon: 1});
                    if(nData){
                    	_this.refreshNode(res.data.id)
                    }else{
                    	_this.refreshParentNode(res.data.parentId)
                    }
                } else {
                    layer.msg(res.message, {icon: 2});
                }
                return false;
            });
        }
    });
}

//预案配置
SceneLayer.prototype.showPlanEdit=function(nData,parentId){
	let _this=this;
	_this.hideRMenu();
	if(_this.editor.scenePlanLibrary){
		_this.editor.scenePlanLibrary.planId = parentId;
		_this.editor.scenePlanLibrary.open();
	}
}

SceneLayer.prototype.showEditPlan=function(nData,parentId){
	let _this=this;
	_this.hideRMenu();
    layer.open({
        type: 1,
        title: (nData ? '修改' : '新增') + '预案',
        content: $('#sceneLayerEditScript').html(),
		offset: '40px',
		area: '280px',
        skin: 'layui-layer layui-layer-city',
        success: function (layero, dIndex) {
			if(nData)
				nData.name = nData.name.replace(/\(.*?\)/g,'');
			if(!parentId){
				form.val('sceneLayerForm', nData);
			}
            form.on('submit(submitSceneLayerForm)', function (data) {
                layer.load(2);
                var formData={}; 
                for(var key in data.field){
                	formData['sceneLayer.'+key]=data.field[key];
                }
                if(!data.field['parentId']){
                	formData['sceneLayer.parentId']=parentId||_this.sceneId;
                }
				formData['sceneLayer.type']='plan';
                formData['sceneLayer.sceneId']=_this.sceneId;
    			var res = common_ajax.ajaxFunc('post', _this.ctx + "/scene/layer/save",formData, "json", null);
                layer.closeAll('loading');
                if (res.code == 200) {
                    layer.close(dIndex);
                    layer.msg(res.message, {icon: 1});
                    if(nData){
                    	_this.refreshNode(res.data.id)
                    }else{
                    	_this.refreshParentNode(res.data.parentId)
                    }
                } else {
                    layer.msg(res.message, {icon: 2});
                }
                return false;
            });
        }
    });
}

SceneLayer.prototype.flyToLayer=function (nData) {
	if(nData && nData.x && nData.y){
		this.globe.flyTo({
			position:{
				x:nData.x*1,
				y:nData.y*1,
				z:nData.z*1
			},
			orientation:{
				heading:nData.heading*1,
				pitch:nData.pitch*1,
				roll:nData.roll*1
			}
		});
	}
}

SceneLayer.prototype.hideRMenu=function () {
	var rMenu = $('#rMenu'); 
	if (rMenu) rMenu.css({"visibility": "hidden"});
}

SceneLayer.prototype.refreshNode=function(id) {
	var zTree = $.fn.zTree.getZTreeObj(this.treeId);
	zTree.reAsyncChildNodes(null, "refresh");
}

/**
 * 刷新当前选择节点的父节点
 */
SceneLayer.prototype.refreshParentNode=function() {
	var zTree = $.fn.zTree.getZTreeObj(this.treeId);
	zTree.reAsyncChildNodes(null, "refresh");
}

SceneLayer.prototype.deleteEmptyFolderNodes=function() {
	var _this = this;
	var zTree = $.fn.zTree.getZTreeObj(this.treeId);
	var nodes = zTree.getNodes();
	if(nodes && nodes.length>0){
		nodes.forEach(function (value){
			if('-1'===value.type || '-2'===value.type){
				if(value.children==null || value.children.length==0){
					common_ajax.ajaxFunc('get', _this.ctx + "/scene/layer/delete", { layerId: value.id }, "json", null);
				}
			}
		});
		zTree.reAsyncChildNodes(null, "refresh");
	}
}

//工具栏按钮事件
SceneLayer.prototype.renderTool=function() {
	let _this=this;
	$('#addScenePlanBtn').click(function() {
		_this.showEditPlan();
	});
	
	$('#addSceneLayerBtn').click(function() {
		_this.showEditFolder();
	});
	
	$('#deleteSceneEmptyLayerBtn').click(function() {
		_this.deleteEmptyFolderNodes();
	});
}


